<?php

/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2023-05-22 15:03:03
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2023-07-06 16:44:43
 */

namespace Common\Job;

use Common\Event\SendToMqtt;
use Common\Event\SendToTcp;
use Common\Helpers\DebugHelper;
use Common\Models\sys\SysProject;
use Common\Services\Sys\DeviceService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\HandlerStack;
use Hyperf\AsyncQueue\Event\Event;
use Hyperf\AsyncQueue\Job;
use Hyperf\Context\ApplicationContext;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\CoroutineHandler;
use Psr\EventDispatcher\EventDispatcherInterface;
use Simps\MQTT\Exception\RuntimeException;

/**
 * 第三方异步通知
 */
class NoticeSdkJob extends Job
{

    public array $params;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;



    public function __construct($params)
    {
        $this->params = $params;

    }

    public function handle(): void
    {
        $params = $this->params;
        DebugHelper::consoleWrite('通知第三方开始-0', $params);
        //事件名称
        $device_mac = $params['device_mac'];

        $deviceInfo = DeviceService::getInfoByMac($device_mac);

        DebugHelper::consoleWrite('通知第三方开始-设备状态', [
            'deviceInfo' => $deviceInfo
        ]);
        $loopback_address = SysProject::query()->where(['id' => $deviceInfo['project_id']])->value('loopback_address');

        DebugHelper::consoleWrite('通知第三方开始-第三方回调地址', [
            'loopback_address' => $loopback_address
        ]);
        if ($loopback_address) {
            $client = new Client([
                'base_uri' => $loopback_address,
                'handler' => HandlerStack::create(new CoroutineHandler()),
                'timeout' => 5,
                'swoole' => [
                    'timeout' => 10,
                    'socket_buffer_size' => 1024 * 1024 * 2,
                ],
            ]);


            try {
                DebugHelper::consoleWrite('通知第三方开始-1', $device_mac);
                $device_status = $deviceInfo->deviceStatus;
                DebugHelper::consoleWrite('通知第三方开始-2', $device_status);
                DebugHelper::consoleWrite('通知第三方开始-数据集合', [
                    'eventName' => 'deviceStatus',
                    'data' => $device_status,
                    'device_id' => $device_status['device_id'],
                    'project_id' => $device_status['project_id'],
                ]);
                $promise = $client->postAsync('', [
                    'form_params' => [
                        'eventName' => 'deviceStatus',
                        'data' => json_decode($device_status),
                        'device_id' => $device_status['device_id'],
                        'project_id' => $device_status['project_id'],
                    ]
                ]);

                $response = $promise->wait();
                $Res = $response->getBody()->getContents();
                DebugHelper::consoleWrite('通知第三方结果', [
                    'res' => $Res
                ]);
            } catch (GuzzleException $e) {
                DebugHelper::consoleWrite('通知失败', $e->getMessage());
            } catch (RuntimeException $e){
                DebugHelper::consoleWrite('通知失败-mqtt', $e->getMessage());
            }
        }


        // 设置任务数据
        DebugHelper::consoleWrite('异步任务消费 ReceptacleJob-handle');

    }
}
